
package testing;

import cfar.actors.Node;
import cfar.actors.distributed.ActorServer;
import cfar.ff.data.Assocs.Assoc2;
import cfar.ff.data.List;
import cfar.ff.fun.F1;
import cfar.ff.fun.F2;
import cfar.ff.fun.Seq;
import cfar.ff.interfaces.Sequence;
import cfar.utils.IO;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.logging.Level;
import java.util.logging.Logger;

import static cfar.ff.fun.Curry.*;

/**
 *
 * @author badi
 */
public class reduce {

    public static F2<Integer,Integer,Integer> add = new F2<Integer, Integer, Integer>() {

        public Integer f(Integer a, Integer b) {
            return a + b;
        }
    };

    public static F1<Assoc2<InetAddress, Integer>, Node> mknode = new F1<Assoc2<InetAddress, Integer>, Node>() {

        public Node f(Assoc2<InetAddress, Integer> a) {
            try {
                return new Node(a.$1, a.$2);
            } catch (IOException ex) {
                Logger.getLogger(reduce.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
    };

    public static F2<String,String,Sequence<List,Node>>
            get_nodes = new F2<String, String, Sequence<List, Node>>() {

        public Sequence<List, Node> f(String path, String suffix) {
            return Seq.parMap(mknode, IO.available_hosts(path, suffix));
        }
    };


    public static String syncdir = "/tmp/cfar.sync",
                         suffix = "cfs";

    public static void main(String[] main) throws IOException{
        new File(syncdir).mkdir();

        for (int i = 0; i < 10; i++) {
            new Thread(new ActorServer(syncdir, suffix)).start();
        }

        List<Node> nodes = (List<Node>) Seq.parMap(mknode, IO.available_hosts(syncdir, suffix));

        List<Integer> s1 = List.list(1,2,3,4,5,6,7,8,9,10);

        int res = Seq.distReduce(curry(curry(get_nodes, syncdir), suffix), add, s1);

        for (Node n : nodes) {
            n.tell(cfar.actors.Message.stop);
        }

        System.out.println("res: " + res);
        System.exit(0);
    }

}
